const { searchRecord, addRecord, getItems } = require('../../utils/feishuAPI');

Page({
  // 页面变量
  data: {
    isLogin: false, // 当前用户是否登录
    userInfo: {}, // 用户个人信息
    classInfo: {}, // 课程信息
    statusText: '暂未分配'
  },
  onLoad: function () {
    // 页面加载时处理
    this.initUser();
    this.updateClassInfo();
  },

  
  onShow: function () {
    console.log("current page: role");
    // 页面显示时更新标题
    const app = getApp();
    app.updateTitle();
  },

  // 获取用户个人信息
  initUser: function() {
    const app = getApp();
    this.setData({
      isLogin: app.globalData.isLogin,
      userInfo: app.globalData.userInfo,
      classInfo: app.globalData.classInfo,
    });
  },

  updateClassInfo: function() {
    const app = getApp()
    const that = this
    console.log(`that.data.isLogin: ${that.data.isLogin}`)
    if (that.data.isLogin) {
      const nickName = that.data.userInfo.nickName;
      console.log(nickName)
      const query = {
        // filter: `${columnName} = '${value}'`
        // filter: `CurrentValue.[${columnName}] = ${value}`
        filter: {
          "conjunction": "and",
          "conditions": [
            {
              "field_name": '姓名',
              "operator": "is",
              "value": [
                nickName
              ]
            }
          ]
        }
      };
      searchRecord('用户信息表', query)
        .then((res) => {
          if (res != 0) {
            r = getItems('用户信息表', res.data.data.items)
            that.data.classInfo = r[0];
            app.globalData.classInfo = that.data.classInfo
            console.log(that.data.classInfo)

            // 将用户信息缓存到本地
            tt.setStorage({
              key: 'classInfo',
              data: app.globalData.classInfo
            })
            console.log("Class info saved to storage");
            if(that.data.classInfo["身份"]) {
              if (that.data.classInfo['身份'] === '助教' || that.data.classInfo['身份'] === '老师') {
                console.log(2)
                // that.data.statusText = that.data.classInfo['身份']
                that.setData({
                  statusText: that.data.classInfo['身份']
                })
              } else {
                that.setData({
                  statusText: `G${that.data.classInfo['组号']}-${that.data.classInfo['组内身份']}`
                })
                // that.data.statusText = `G${that.data.classInfo['组号']}-${that.data.classInfo['组内身份']}`
              }
              app.globalData.isClassLogin = true
              app.updateGoal()
            }else{
              console.log('暂未分配')
            }
          } else {
            addRecord('用户信息表', [nickName, '', '', ''])
            console.log('search fail')
          }
        })
    } else {

    }
  },

  // 用户登录
  toLogin() {
    const that = this;
    tt.login({
      success: (res) => {
        tt.getUserInfo({
          success: (res) => {
            const userInfo = JSON.parse(res.rawData);
            that.setData({
              isLogin: true,
              userInfo: userInfo
            });
            // 更新全局数据
            const app = getApp();
            app.globalData.isLogin = true;
            app.globalData.userInfo = userInfo;

            // 将用户信息缓存到本地
            tt.setStorage({
              key: 'userInfo',
              data: app.globalData.userInfo
            })
            console.log("User info saved to storage");
            
            // 登录页面时更新标题
            app.updateTitle();

            // 登陆页面更新身份
            that.updateClassInfo()
            tt.showToast({
              title: 'login success',
              icon: 'success',
              success: () => {
                console.log("login success");
              }
            });
          },
          fail: (res) => {
            console.log(res);
          }
        });
      },
      fail: (res) => {
        console.log(`login fail`);
      }
    });
    
  },
  // 显示退出登录选项
  showLogoutOption: function() {
    const that = this;
    tt.showActionSheet({
      itemList: ['退出登录'],
      success: function(res) {
        if (res.tapIndex === 0) {
          that.logout();
        }
      }
    });
  },
  // 退出登录操作
  logout: function() {
    this.setData({
      isLogin: false,
      userInfo: {}
    });
    // 更新全局数据
    const app = getApp();
    app.globalData.isLogin = false;
    app.globalData.userInfo = {};
    app.globalData.classInfo = {};
    
    // 移除本地缓存中的用户信息
    tt.removeStorage({
      key: 'userInfo',
      success() {
        console.log('User info removed from storage');
      }
    });
    tt.removeStorage({
      key: 'classInfo',
      success() {
        console.log('Class info removed from storage');
      }
    });
    app.updateTitle();
  },
});